import request from '@/config/axios'
import { getApiPath } from '@/config/api'

export default {
  namespaced: true,

  state: {
    dailyNutrition: {
      calories: 0,
      caloriesProgress: 0,
      carbs: 0,
      carbsProgress: 0,
      fat: 0,
      fatProgress: 0,
      protein: 0,
      proteinProgress: 0
    },
    goalProgress: {
      current: '',
      percentage: 0,
      status: '',
      statusText: '',
      target: '',
      type: ''
    },
    recentMeals: [],
    weightTrend: [],
    loading: false
  },

  mutations: {
    SET_DASHBOARD_DATA(state, data) {
      state.dailyNutrition = data.dailyNutrition
      state.goalProgress = data.goalProgress
      state.recentMeals = data.recentMeals
      state.weightTrend = data.weightTrend
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_WEIGHT_TREND(state, data) {
      state.weightTrend = data
    },
    SET_DAILY_NUTRITION(state, data) {
      state.dailyNutrition = data
    },
    SET_GOAL_PROGRESS(state, data) {
      state.goalProgress = data
    },
    SET_RECENT_MEALS(state, data) {
      state.recentMeals = data
    }
  },

  actions: {
    async getDashboardData({ commit }) {
      try {
        commit('SET_LOADING', true)
        const userId = localStorage.getItem('userId')
        if (!userId) {
          throw new Error('用户未登录')
        }

        const res = await request({
          url: getApiPath('DASHBOARD'),
          method: 'get',
          params: {
            userId: parseInt(userId)
          }
        })

        if (res.code === 200 && res.data) {
          commit('SET_DASHBOARD_DATA', res.data)
          if (res.data.weightTrend) {
            commit('SET_WEIGHT_TREND', res.data.weightTrend)
          }
          return res.data
        }
        throw new Error(res.message || '获取仪表盘数据失败')
      } catch (error) {
        console.error('获取仪表盘数据失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    async getWeightTrend({ commit }, { range = 'week' } = {}) {
      try {
        const userId = localStorage.getItem('userId')
        if (!userId) {
          throw new Error('用户未登录')
        }

        const res = await request({
          url: getApiPath('WEIGHT_TREND'),
          method: 'get',
          params: {
            userId: parseInt(userId),
            type: range
          }
        })

        if (res.code === 200 && res.data) {
          commit('SET_WEIGHT_TREND', res.data)
          return res.data
        }
        throw new Error(res.message || '获取体重趋势失败')
      } catch (error) {
        console.error('获取体重趋势失败:', error)
        throw error
      }
    },

    updateWeightTrend({ commit }, data) {
      commit('SET_WEIGHT_TREND', data)
    }
  }
} 